package org.dev.vlp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.dev.vlp.constants.CachePrefix;
import org.dev.vlp.constants.Common;
import org.dev.vlp.constants.LanguageEnum;
import org.dev.vlp.entity.*;
import org.dev.vlp.entity.Character;
import org.dev.vlp.mapper.*;
import org.dev.vlp.service.StatisticsService;
import org.dev.vlp.utils.RedisUtils;
import org.dev.vlp.vo.DailyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
* @author 86184
* @description 针对表【vlp_statistics】的数据库操作Service实现
* @createDate 2023-01-15 17:42:26
*/
@Service
public class StatisticsServiceImpl extends ServiceImpl<StatisticsMapper, Statistics>
    implements StatisticsService{

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private StatisticsMapper statisticsMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private CharacterMapper characterMapper;

    @Autowired
    private SayingMapper sayingMapper;

    @Autowired
    private PoemMapper poemMapper;

    @Autowired
    private SongMapper songMapper;

    @Autowired
    private ProverbMapper proverbMapper;

    @Autowired
    private SecenryMapper sceneryMapper;

    @Override
    public int getLan(int userId) {
        Object lanId = redisUtils.get(String.format(CachePrefix.LAN_PREFIX, userId));
        if(lanId==null){
            QueryWrapper<Statistics> statisticsQueryWrapper = new QueryWrapper<>();
            statisticsQueryWrapper.eq("user_id",userId)
                    .orderByDesc("gmt_modified")
                    .last("limit 1");
            Statistics statistics = statisticsMapper.selectOne(statisticsQueryWrapper);
            if(statistics==null){
                return 0;
            }else{
                Integer lanId1 = statistics.getLanId();
                redisUtils.set(String.format(CachePrefix.LAN_PREFIX, userId), lanId1, 60 * 60 * 24 * 7);
                return lanId1;
            }
        }else{
            return (int)lanId;
        }
    }

    @Override
    public void setLan(int userId, int lanId) {
        // 切换语种，即以前有过该语种的选择，先在mysql里面查询，更新它的最新时间，方便上面的获取语种函数，更新redis
        QueryWrapper<Statistics> statisticsQueryWrapper = new QueryWrapper<>();
        statisticsQueryWrapper.eq("user_id",userId).eq("lan_id",lanId).orderByDesc("gmt_modified")
                .last("limit 1");
        Statistics statistics1 = statisticsMapper.selectOne(statisticsQueryWrapper);
        if(statistics1!=null){
            statistics1.setGmtModified(new Date());
            statisticsMapper.updateById(statistics1);
            redisUtils.set(String.format(CachePrefix.LAN_PREFIX, userId), lanId, 60 * 60 * 24 * 7);
            return;
        }
        // 设置语种，即以前没有选择过该语种，存redis
        LanguageEnum languageEnum = LanguageEnum.get(lanId);
        int bookId=languageEnum.getBookIdEnum().getBookId();
        Statistics statistics = new Statistics(userId,lanId,bookId);
        statisticsMapper.insert(statistics);
        redisUtils.set(String.format(CachePrefix.LAN_PREFIX, userId), lanId, 60 * 60 * 24 * 7);
    }

    @Override
    public Statistics getBook(int userId) {
        QueryWrapper<Statistics> statisticsQueryWrapper = new QueryWrapper<>();
        int lan = getLan(userId);
        statisticsQueryWrapper.eq("user_id",userId)
                .eq("lan_id",lan)
                .orderByDesc("gmt_modified")
                .last("limit 1");
        return statisticsMapper.selectOne(statisticsQueryWrapper);
    }

    @Override
    public DailyVo getDailyData(int lan,int uid) throws ParseException {
        User user = userMapper.selectById(uid);
        String dailyChoice = user.getDailyChoice();
        String[] split = dailyChoice.split("-");
        if(lan==0){
            lan = getLan(uid);
//            lan=1;
        }
        // 计算天数
        Date date=null;
        String start= Common.startTime;
        SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd");
        date=formatter.parse(start);
        Date current=new Date();
        Long starTime=date.getTime();
        Long endTime=current.getTime();
        Long num=endTime-starTime;//时间戳相差的毫秒数
        Long sub=num/24/60/60/1000;
        DailyVo dailyVo = new DailyVo();
        // 计算每日人物总数，如果相减结果大于总数，则取余，否则取该人物
        // 其他每日系列如法炮制
        if(split[0].equals("1")){
            QueryWrapper<Character> characterWrapper = new QueryWrapper<>();
            characterWrapper.eq("lan",lan);
            Long count = characterMapper.selectCount(characterWrapper);
            characterWrapper.clear();
            if(count!=0){
                if(count==1){
                    characterWrapper.eq("lan",lan).last("limit 1");
                }else{
                    if(sub<=count){
                        characterWrapper.eq("lan",lan).last("limit "+String.valueOf(sub-1)+",1");
                    }else{
                        if(sub%count==0){
                            characterWrapper.eq("lan",lan).last("limit "+String.valueOf(count-1)+",1");
                        }else{
                            characterWrapper.eq("lan",lan).last("limit "+String.valueOf(sub%count-1)+",1");
                        }
                    }
                }
                Character character = characterMapper.selectOne(characterWrapper);
                //        LanguageEnum languageEnum = LanguageEnum.get(lan);
//            String characterTable = languageEnum.getCharacterEnum().getTableName();
//            Character randomCharacter = characterMapper.getRandomCharacter(characterTable);
                dailyVo.setCharacter(character);
            }
        }
        if(split[1].equals("1")){
            QueryWrapper<Saying> sayingWrapper = new QueryWrapper<>();
            sayingWrapper.eq("lan",lan);
            Long count = sayingMapper.selectCount(sayingWrapper);
            sayingWrapper.clear();
            if(count!=0) {
                if (count == 1) {
                    sayingWrapper.eq("lan", lan).last("limit 1");
                } else {
                    if (sub <= count) {
                        sayingWrapper.eq("lan", lan).last("limit " + String.valueOf(sub - 1) + ",1");
                    } else {
                        if (sub % count == 0) {
                            sayingWrapper.eq("lan", lan).last("limit " + String.valueOf(count - 1) + ",1");
                        } else {
                            sayingWrapper.eq("lan", lan).last("limit " + String.valueOf(sub % count - 1) + ",1");
                        }
                    }
                }
                Saying saying = sayingMapper.selectOne(sayingWrapper);
                dailyVo.setSaying(saying);
            }
        }
        if(split[2].equals("1")){
            QueryWrapper<Poem> sayingWrapper = new QueryWrapper<>();
            sayingWrapper.eq("lan",lan);
            Long count = poemMapper.selectCount(sayingWrapper);
            sayingWrapper.clear();
            if(count!=0) {
                if (count == 1) {
                    sayingWrapper.eq("lan", lan).last("limit 1");
                } else {
                    if (sub <= count) {
                        sayingWrapper.eq("lan", lan).last("limit " + String.valueOf(sub - 1) + ",1");
                    } else {
                        if (sub % count == 0) {
                            sayingWrapper.eq("lan", lan).last("limit " + String.valueOf(count - 1) + ",1");
                        } else {
                            sayingWrapper.eq("lan", lan).last("limit " + String.valueOf(sub % count - 1) + ",1");
                        }
                    }
                }
                Poem saying = poemMapper.selectOne(sayingWrapper);
                dailyVo.setPoem(saying);
            }
        }
        if(split[3].equals("1")){
            QueryWrapper<Proverb> sayingWrapper = new QueryWrapper<>();
            sayingWrapper.eq("lan",lan);
            Long count = proverbMapper.selectCount(sayingWrapper);
            sayingWrapper.clear();
            if(count!=0) {
                if (count == 1) {
                    sayingWrapper.eq("lan", lan).last("limit 1");
                } else {
                    if (sub <= count) {
                        sayingWrapper.eq("lan", lan).last("limit " + String.valueOf(sub - 1) + ",1");
                    } else {
                        if (sub % count == 0) {
                            sayingWrapper.eq("lan", lan).last("limit " + String.valueOf(count - 1) + ",1");
                        } else {
                            sayingWrapper.eq("lan", lan).last("limit " + String.valueOf(sub % count - 1) + ",1");
                        }
                    }
                }
                Proverb saying = proverbMapper.selectOne(sayingWrapper);
                dailyVo.setProverb(saying);
            }
        }
        if(split[4].equals("1")){
            QueryWrapper<Song> sayingWrapper = new QueryWrapper<>();
            sayingWrapper.eq("lan",lan);
            Long count = songMapper.selectCount(sayingWrapper);
            sayingWrapper.clear();
            if(count!=0) {
                if (count == 1) {
                    sayingWrapper.eq("lan", lan).last("limit 1");
                } else {
                    if (sub <= count) {
                        sayingWrapper.eq("lan", lan).last("limit " + String.valueOf(sub - 1) + ",1");
                    } else {
                        if (sub % count == 0) {
                            sayingWrapper.eq("lan", lan).last("limit " + String.valueOf(count - 1) + ",1");
                        } else {
                            sayingWrapper.eq("lan", lan).last("limit " + String.valueOf(sub % count - 1) + ",1");
                        }
                    }
                }
                Song saying = songMapper.selectOne(sayingWrapper);
                dailyVo.setSong(saying);
            }
        }
        if(split[5].equals("1")){
            QueryWrapper<Secenry> sayingWrapper = new QueryWrapper<>();
            sayingWrapper.eq("lan",lan);
            Long count = sceneryMapper.selectCount(sayingWrapper);
            sayingWrapper.clear();
            if(count!=0) {
                if (count == 1) {
                    sayingWrapper.eq("lan", lan).last("limit 1");
                } else {
                    if (sub <= count) {
                        sayingWrapper.eq("lan", lan).last("limit " + String.valueOf(sub - 1) + ",1");
                    } else {
                        if (sub % count == 0) {
                            sayingWrapper.eq("lan", lan).last("limit " + String.valueOf(count - 1) + ",1");
                        } else {
                            sayingWrapper.eq("lan", lan).last("limit " + String.valueOf(sub % count - 1) + ",1");
                        }
                    }
                }
                Secenry saying = sceneryMapper.selectOne(sayingWrapper);
                dailyVo.setSecenry(saying);
            }
        }
//        System.out.println(dailyVo);
        return dailyVo;
    }
}




